package com.qf.controller;

import cn.dsna.util.images.ValidateCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/code")
public class CodeController extends BaseServlet {

    public CodeController() {
        System.out.println("一个servlet出现了");
    }


    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ValidateCode code = new ValidateCode(120, 30, 4, 20);
        //2.获取生成的验证码的字符串值
        String code1= code.getCode();
        //抛出一个问题？验证码的时效性
        //而一个用户只有一个session对象，如果你让该用户的session失效，那么后去登录状态的保持怎么办？
        Cookie cookie=new Cookie("code",code1);
        cookie.setMaxAge(10*60);//设置有效时长为
        response.addCookie(cookie);
       /* HttpSession session = request.getSession();
        session.setAttribute("code",code1);
        session.setMaxInactiveInterval(30);*/
        System.out.println(code1); //获取正确值
        //3.响应写回验证图片
        code.write(response.getOutputStream());
    }

    public String checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");
        String code1="";
        Cookie[] cookies = request.getCookies();
        for(Cookie c:cookies){
            if("code".equals(c.getName())){
                code1=c.getValue();
            }
        }
        if(code.equalsIgnoreCase(code1)){
           return String.valueOf(1);
        }else{
            return String.valueOf(0);
        }
    }

}
